﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Net;

namespace Nwsfeed
{
    public class FeedXmlReader
    {
        public FeedXmlReader()
        { 
        }

        public static string ExtractDomainNameFromURL(string Url)
        {
            if (!Url.Contains("://"))
                Url = "http://" + Url;

            return new Uri(Url).Host;
        }

        public RSSFeed Load(String doc, Uri uri)
        {
            RSSFeed feed = new RSSFeed();

            
            XDocument document = XDocument.Load(new StringReader(doc));


            // TO DO: add ATOM support
            // RSS
            feed.Uri = uri.ToString();
            String encoding = null;
            if (document.Declaration != null)
            {
                encoding = document.Declaration.Encoding;
                if (encoding != null)
                {
                    MyWebClient client = new MyWebClient();
                    client.Encoding = Encoding.GetEncoding(encoding);
                    doc = client.DownloadString(uri.ToString());

                    document = XDocument.Load(new StringReader(doc));
                }
            }



            if (encoding != null)
                feed.Encoding = encoding;

            if (document.Root.Element("channel").Element("title") != null)
                feed.Title = document.Root.Element("channel").Element("title").Value;

            if (document.Root.Element("channel").Element("description") != null)
                feed.Summary = document.Root.Element("channel").Element("description").Value;

            if (document.Root.Element("channel").Element("link") != null)
                feed.HomepageUri = document.Root.Element("channel").Element("link").Value;

            if (feed.HomepageUri != null)
            {
                String path = NwsfeedApp.WorkingDirectory + "\\cache\\img_" + feed.Title.ToLower() + ".ico";
                long size = 0;
                try
                {
                    size = new FileInfo(path).Length;
                }
                catch {
                    size = 0;
                }

                if (size == 0)
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://g.etfv.co/" + feed.HomepageUri + "?defaulticon=none");

                    using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                    {
                        if (res.StatusCode == HttpStatusCode.OK)
                        {
                            MyWebClient client = new MyWebClient();
                            try
                            {
                                client.DownloadFile("http://g.etfv.co/" + feed.HomepageUri + "?defaulticon=none", "cache\\img_" + feed.Title.ToLower() + ".ico");
                                size = new FileInfo(path).Length;
                            }
                            catch
                            {
                                size = 0;
                            }
                        }
                    }
                }
                if (size != 0)
                    feed.ImageCacheUri = path;
                else
                    feed.ImageCacheUri = null;
            }           


            IEnumerable<XElement> items = document.Root.Element("channel").Elements("item");

            foreach (XElement elem in items)
            {
                FeedItem item = new FeedItem(
                    elem.Element("title").Value,
                    elem.Element("description").Value,
                    elem.Element("link").Value,
                    elem.Element("pubDate").Value);
                feed.Posts.Add(item);
            }

            feed.IsLoading = false;

            return feed;
        }
    }
}
